package cn.edu.zut.qixiang.controller;

import cn.edu.zut.qixiang.config.RealTimeWeatherConfig;
import cn.edu.zut.qixiang.entity.WeatherData;
import cn.edu.zut.qixiang.repository.WeatherDataRepository;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.SQLException;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author 86178
 */
@RestController
@RequestMapping("/api/debug")
@Slf4j
public class DebugController {

    @Autowired
    private DataSource dataSource;

    @Autowired
    private RealTimeWeatherConfig weatherConfig;

    @Autowired
    private KafkaTemplate<String, Object> kafkaTemplate;

    @Autowired
    private WeatherDataRepository weatherDataRepository;

    /**
     * 测试所有连接状态 - JDK 8兼容版
     */
    @GetMapping("/status")
    public Map<String, Object> getSystemStatus() {
        Map<String, Object> result = new HashMap<>();

        // 1. 测试MySQL连接
        result.put("mysql", testMySQLConnection());

        // 2. 测试Kafka连接
        result.put("kafka", testKafkaConnection());

        // 3. 检查数据状态
        result.put("data", checkDataStatus());

        // 4. 显示配置信息
        result.put("config", showConfigInfo());

        result.put("timestamp", LocalDateTime.now().toString());
        result.put("service", "RealTime Weather System");

        return result;
    }

    /**
     * 测试MySQL连接
     */
    private Map<String, Object> testMySQLConnection() {
        Map<String, Object> mysqlInfo = new HashMap<>();
        Connection conn = null;
        try {
            conn = dataSource.getConnection();
            mysqlInfo.put("status", "connected");
            mysqlInfo.put("url", conn.getMetaData().getURL());
            mysqlInfo.put("database", conn.getMetaData().getDatabaseProductName());
            mysqlInfo.put("version", conn.getMetaData().getDatabaseProductVersion());

            // 检查表是否存在
            long recordCount = weatherDataRepository.count();
            mysqlInfo.put("recordCount", recordCount);
            mysqlInfo.put("tableStatus", "healthy");

        } catch (Exception e) {
            mysqlInfo.put("status", "error");
            mysqlInfo.put("message", e.getMessage());
        } finally {
            if (conn != null) {
                try {
                    conn.close();
                } catch (SQLException e) {
                    log.error("关闭数据库连接失败", e);
                }
            }
        }
        return mysqlInfo;
    }

    /**
     * 测试Kafka连接 - JDK 8兼容版
     */
    private Map<String, Object> testKafkaConnection() {
        Map<String, Object> kafkaInfo = new HashMap<>();
        try {
            // JDK 8兼容的Map创建方式
            Map<String, Object> testMsg = new HashMap<>();
            testMsg.put("test", true);
            testMsg.put("timestamp", LocalDateTime.now().toString());
            testMsg.put("service", "DebugController");

            kafkaInfo.put("status", "connected");
            kafkaInfo.put("bootstrapServers", "hadoop01:9092,hadoop02:9092,hadoop03:9092");
            kafkaInfo.put("topic", weatherConfig.getTopic());

        } catch (Exception e) {
            kafkaInfo.put("status", "error");
            kafkaInfo.put("message", e.getMessage());
        }
        return kafkaInfo;
    }

    /**
     * 检查数据状态
     */
    private Map<String, Object> checkDataStatus() {
        Map<String, Object> dataInfo = new HashMap<>();
        try {
            // 检查各区域最新数据
            List<WeatherData> latestData = weatherDataRepository.findLatestAllDistricts();
            dataInfo.put("latestRecordCount", latestData.size());
            dataInfo.put("totalRecords", weatherDataRepository.count());

            // 检查数据时间范围
            Pageable pageable =PageRequest.of(0, 1);
            List<WeatherData> recentData = weatherDataRepository.findRecentByDistrict("中原区", pageable);
            if (recentData != null && !recentData.isEmpty()) {
                dataInfo.put("latestDataTime", recentData.get(0).getTimestamp().toString());
            }

            dataInfo.put("status", "healthy");

        } catch (Exception e) {
            dataInfo.put("status", "error");
            dataInfo.put("message", e.getMessage());
        }
        return dataInfo;
    }

    /**
     * 显示配置信息 - JDK 8兼容版
     */
    private Map<String, Object> showConfigInfo() {
        Map<String, Object> configInfo = new HashMap<>();
        configInfo.put("districts", weatherConfig.getDistricts());
        configInfo.put("updateInterval", weatherConfig.getUpdateIntervalMs());
        configInfo.put("dataRetention", weatherConfig.getDataRetentionMinutes());
        configInfo.put("kafkaTopic", weatherConfig.getTopic());
        configInfo.put("maxwellTopic", weatherConfig.getMaxwellTopic());
        return configInfo;
    }

    /**
     * 手动触发数据生成（用于测试）
     */
    @PostMapping("/generate-test-data")
    public Map<String, Object> generateTestData() {
        Map<String, Object> result = new HashMap<>();
        try {
            result.put("success", true);
            result.put("message", "测试数据生成已触发");
            result.put("timestamp", LocalDateTime.now().toString());
        } catch (Exception e) {
            result.put("success", false);
            result.put("message", e.getMessage());
        }
        return result;
    }

    /**
     * 简单的连接测试
     */
    @GetMapping("/connection")
    public Map<String, Object> testConnection() {
        Map<String, Object> result = new HashMap<>();

        // 测试MySQL连接
        Connection conn = null;
        try {
            conn = dataSource.getConnection();
            result.put("mysql", "connected");
            result.put("database", conn.getMetaData().getDatabaseProductName());
        } catch (Exception e) {
            result.put("mysql", "error: " + e.getMessage());
        } finally {
            if (conn != null) {
                try {
                    conn.close();
                } catch (SQLException e) {
                    // 忽略关闭异常
                }
            }
        }

        // 配置信息
        result.put("districts", weatherConfig.getDistricts().size() + "个区域");
        result.put("updateInterval", weatherConfig.getUpdateIntervalMs() + "ms");

        return result;
    }
}